package com.uziot.bucket.flowable.controller;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.DeploymentBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shidt
 * @version V1.0
 * @className FlowableTaskController
 * @date 2020-12-24 22:59:39
 * @description
 */
@Slf4j
@RestController
public class FlowableTaskController {
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Qualifier("processEngine")
    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private TaskService taskService;

    /**
     * 流程在线部署
     *
     * @param filePath 文件路径
     * @return 部署后的消息返回
     */
    public Deployment deployFlow(String filePath) {
        try {
            DeploymentBuilder deploymentBuilder = repositoryService
                    .createDeployment()
                    .addClasspathResource(filePath);
            Deployment deployment = deploymentBuilder.deploy();
            log.info("成功：部署工作流成：" + filePath);
            return deployment;
        } catch (Exception e) {
            log.error("失败：部署工作流：" + e);
            return null;
        }
    }


    /**
     * 我发起的流程实例列表
     *
     * @param userId userId
     * @return List
     */
    public List<HistoricProcessInstance> getMyStartProcint(String userId) {
        // 历史相关Service
        List<HistoricProcessInstance> list = processEngine.getHistoryService()
                .createHistoricProcessInstanceQuery()
                // .finished() 已完成的 unfinish 未完成的，或者不加表示全部
                .startedBy(userId)
                .orderByProcessInstanceStartTime().asc()
                .list();
        log.info("根据用户ID查询用户发起的流程实例：{}", JSON.toJSONString(list));
        return list;
    }

    /**
     * 查询指定用户参与的流程信息 （流程历史  用户参与 ）
     *
     * @param userId userId
     * @return queryUserJoinFlow
     */
    public List<HistoricProcessInstance> queryUserJoinFlow(String userId) {
        int firstResult = 1;
        int maxResults = 100;
        List<HistoricProcessInstance> historicProcessInstances = historyService
                .createHistoricProcessInstanceQuery().involvedUser(userId)
                .orderByProcessInstanceStartTime().desc().listPage(firstResult, maxResults);
        log.info("查询指定用户参与的流程信息：{}", historicProcessInstances);
        return historicProcessInstances;

    }

    /**
     * 提前终止流程实例
     *
     * @param processInstanceId processInstanceId
     */
    public void deleteProcessInstanceById(String processInstanceId) {
        // ""这个参数本来可以写删除原因
        runtimeService.deleteProcessInstance(processInstanceId, "");
    }

    public void callBack(String processInstanceId, List<String> curTaskKeys, String targetTaskKey) {
        runtimeService.createChangeActivityStateBuilder()
                .processInstanceId(processInstanceId)
                .moveActivityIdsToSingleActivityId(curTaskKeys, targetTaskKey)
                .changeState();
    }

    /**
     * 挂起流程实例
     *
     * @param processInstanceId processInstanceId
     */
    public void handUpProcessInstance(String processInstanceId) {
        runtimeService.suspendProcessInstanceById(processInstanceId);
    }

    /**
     * 恢复（唤醒）被挂起的流程实例
     *
     * @param processInstanceId processInstanceId
     */
    public void activateProcessInstance(String processInstanceId) {
        runtimeService.activateProcessInstanceById(processInstanceId);
    }


    /**
     * 任务转手业务
     *
     * @param taskId       taskId
     * @param curUserId    curUserId
     * @param acceptUserId acceptUserId
     */
    public void setOwner(String taskId, String curUserId, String acceptUserId) {
        // 转办任务
        taskService.setOwner(taskId, curUserId);
        taskService.setAssignee(taskId, acceptUserId);

        // 委派任务：是将任务节点分给其他人处理，等其他人处理好之后，委派任务会自动回到委派人的任务中
        taskService.setOwner(taskId, curUserId);
        taskService.delegateTask(taskId,acceptUserId);

        // 被委派任务的办理:   办理完成后，委派任务会自动回到委派人的任务中
        Map<String, Object> variables = new HashMap<>(1);
        taskService.resolveTask(taskId, variables);
    }
}
